﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using Centido.Core.Dto;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Centido.Core.Test
{
    /// <summary>
    ///   Testing the data transfer object for a unit.
    /// </summary>
    [TestClass]
    public class UnitDtoTest : GenericDtoTest
    {
        /// <summary>
        ///   The current domain name.
        /// </summary>
        public const string DomainName = "FullAdminRights";

        /// <summary>
        ///   The current domain.
        /// </summary>
        private Domain _domain;


        /// <summary>
        /// Test initialiaze
        /// </summary>
        [TestInitialize]
        public void Initialize()
        {
            _domain = Domain.Build(DomainConfiguration.Load(DomainName));

            _domain.DeleteAll();
        }


        /// <summary>
        /// Test clean up
        /// </summary>
        [TestCleanup]
        public void CleanUp()
        {
            _domain.DeleteAll();
        }


        /// <summary>
        ///   Retrieves the name of the data transfer object xml tag.
        /// </summary>
        /// <returns></returns>
        protected override string GetXmlTag()
        {
            return UnitDto.XmlTag;
        }


        /// <summary>
        ///   Retrives the current xml schema version.
        /// </summary>
        /// <returns></returns>
        protected override string GetCurrentXmlSchemaVersion()
        {
            return UnitDto.CurrentXmlSchemaVersion;
        }


        /// <summary>
        ///   Creates a new data transfer object.
        /// </summary>
        /// <returns></returns>
        protected override DataTransferObject CreateDto()
        {
            return new UnitDto
            {
                Name = StringProperty.RandomIdentifier().ToLower(),
                DisplayName = StringProperty.RandomIdentifier()
            };
        }


        /// <summary>
        ///   Retrieves the list of data transfer object fields.
        /// </summary>
        /// <returns></returns>
        protected override IEnumerable<DtoFieldInfo> GetFields()
        {
            yield return new DtoFieldInfo
            {
                Name = "Name",
                XmlName = UnitDto.NameAttribute,
                IsRequired = true,
                FieldType = DtoFieldType.String,
                SampleValue = "unit_name"
            };

            yield return new DtoFieldInfo
            {
                Name = "DisplayName",
                XmlName = UnitDto.DisplayNameAttribute,
                IsRequired = false,
                FieldType = DtoFieldType.String,
                SampleValue = "Display name"
            };
        }


        /// <summary>
        ///   Copies the properties of the data transfer object to the corresponding object.
        /// </summary>
        /// <param name="dto">The data transfer object.</param>
        /// <returns>Returns the corresponding object after copying.</returns>
        protected override object CopyFrom(DataTransferObject dto)
        {
            var unit = _domain.AddUnit("my_name");
            unit.DisplayName = "The unit display name";

            ((UnitDto)dto).CopyTo(unit);

            return unit;
        }


        /// <summary>
        ///   Creates a data transfer object from the correpsonding object.
        /// </summary>
        /// <param name="dto">The created data transfer object.</param>
        /// <param name="initialObject">The initial object.</param>
        protected override void CreateDtoFromObject(out DataTransferObject dto, out object initialObject)
        {
            var unit = _domain.AddUnit("my_name");
            unit.DisplayName = "The unit display name";

            dto = UnitDto.CreateFrom(unit);
            initialObject = unit;
        }


        /// <summary>
        ///   Reading unit users from xml.
        /// </summary>
        [TestMethod]
        public void ReadingUnitUserListFromXml()
        {
            // Creating the unit
            var xml = string.Format("<{0} {1}=\"{2}\">",
                UnitDto.XmlTag,
                UnitDto.NameAttribute,
                StringProperty.RandomIdentifier());

            // Creating the user list
            xml += string.Format("<{0}><{1} {2}=\"{3}\" /><{4} {5}=\"{6}\"></{7}></{8}></{9}>",
                UnitDto.UserListTag,
                UnitDto.UserTag,
                UnitDto.UserNameAttribute,
                StringProperty.RandomIdentifier(),
                UnitDto.UserTag,
                UnitDto.UserNameAttribute,
                StringProperty.RandomIdentifier(),
                UnitDto.UserTag,
                UnitDto.UserListTag,
                UnitDto.XmlTag);

            var stream = new XmlTextReader(new MemoryStream(Encoding.UTF8.GetBytes(xml)));

            var unitDto = new UnitDto();

            unitDto.ReadXml(stream);

            Assert.AreEqual(unitDto.UserNames.Count(), 2);
        }


        /// <summary>
        ///   Reading an empty user list from xml.
        /// </summary>
        [TestMethod]
        public void ReadingEmptyUserListFromXml()
        {
            var xml = string.Format("<{0} {1}=\"{2}\">",
               UnitDto.XmlTag,
               UnitDto.NameAttribute,
               StringProperty.RandomIdentifier());

            // Creating an empty user list
            xml += string.Format("<{0} /></{1}>",
                UnitDto.UserListTag,
                UnitDto.XmlTag);

            var stream = new XmlTextReader(new MemoryStream(Encoding.UTF8.GetBytes(xml)));

            var roleDto = new UnitDto();

            roleDto.ReadXml(stream);

            Assert.AreEqual(roleDto.UserNames.Count(), 0);
        }


        /// <summary>
        ///   Writing and reading the user list.
        /// </summary>
        [TestMethod]
        public void WritingAndReadingUserList()
        {
            var unitDto = new UnitDto
            {
                Name = StringProperty.RandomIdentifier()
            };

            unitDto.AddUser(StringProperty.RandomIdentifier());
            unitDto.AddUser(StringProperty.RandomIdentifier());

            var memoryStream = new MemoryStream();
            var writer = new XmlTextWriter(memoryStream, Encoding.UTF8);

            unitDto.WriteXml(writer);

            writer.Flush();

            memoryStream.Position = 0;
            var streamReader = new StreamReader(memoryStream);
            var xml = streamReader.ReadToEnd();

            Assert.IsFalse(string.IsNullOrEmpty(xml));

            memoryStream.Position = 0;
            var reader = new XmlTextReader(memoryStream);

            var dto = new UnitDto();

            dto.ReadXml(reader);

            Assert.AreEqual(dto.UserNames.Count(), 2);
        }


        /// <summary>
        ///   Reading child unit list from xml.
        /// </summary>
        [TestMethod]
        public void ReadingChildUnitListFromXml()
        {
            // Creating the unit
            var xml = string.Format("<{0} {1}=\"{2}\">",
                UnitDto.XmlTag,
                UnitDto.NameAttribute,
                StringProperty.RandomIdentifier());

            // Creating the child unit list
            xml += string.Format("<{0}><{1} {2}=\"{3}\" /><{4} {5}=\"{6}\"></{7}></{8}></{9}>",
                UnitDto.ChildUnitListTag,
                UnitDto.ChildUnitTag,
                UnitDto.ChildUnitNameAttribute,
                StringProperty.RandomIdentifier(),
                UnitDto.ChildUnitTag,
                UnitDto.ChildUnitNameAttribute,
                StringProperty.RandomIdentifier(),
                UnitDto.ChildUnitTag,
                UnitDto.ChildUnitListTag,
                UnitDto.XmlTag);

            var stream = new XmlTextReader(new MemoryStream(Encoding.UTF8.GetBytes(xml)));

            var roleDto = new UnitDto();

            roleDto.ReadXml(stream);

            Assert.AreEqual(roleDto.ChildUnitNames.Count(), 2);
        }


        /// <summary>
        ///   Reading an empty child unit list from xml.
        /// </summary>
        [TestMethod]
        public void ReadingEmptyChildUnitListFromXml()
        {
            var xml = string.Format("<{0} {1}=\"{2}\">",
               UnitDto.XmlTag,
               UnitDto.NameAttribute,
               StringProperty.RandomIdentifier());

            // Creating an empty child unit list
            xml += string.Format("<{0} /></{1}>",
                UnitDto.ChildUnitListTag,
                UnitDto.XmlTag);

            var stream = new XmlTextReader(new MemoryStream(Encoding.UTF8.GetBytes(xml)));

            var roleDto = new UnitDto();

            roleDto.ReadXml(stream);

            Assert.AreEqual(roleDto.ChildUnitNames.Count(), 0);
        }


        /// <summary>
        ///   Writing and reading the child unit list.
        /// </summary>
        [TestMethod]
        public void WritingAndReadingChildUnitList()
        {
            var unitDto = new UnitDto
            {
                Name = StringProperty.RandomIdentifier()
            };

            unitDto.AddChildUnit("child_1");
            unitDto.AddChildUnit("child_2");

            var memoryStream = new MemoryStream();
            var writer = new XmlTextWriter(memoryStream, Encoding.UTF8);

            unitDto.WriteXml(writer);

            writer.Flush();

            memoryStream.Position = 0;
            var streamReader = new StreamReader(memoryStream);
            var xml = streamReader.ReadToEnd();

            Assert.IsFalse(string.IsNullOrEmpty(xml));

            memoryStream.Position = 0;
            var reader = new XmlTextReader(memoryStream);

            var dto = new UnitDto();

            dto.ReadXml(reader);

            Assert.AreEqual(dto.ChildUnitNames.Count(), 2);
            Assert.AreEqual(dto.ChildUnitNames.Count(u => u == "child_1"), 1);
            Assert.AreEqual(dto.ChildUnitNames.Count(u => u == "child_2"), 1);
        }
    }
}
